package cn.asura.controller;

import cn.asura.pojo.BlogType;
import cn.asura.pojo.User;
import cn.asura.service.BlogService;
import cn.asura.service.BlogTypeService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Sakura
 * @description
 * @createTime 2020-09-18 23:21
 */
@Controller
@RequestMapping("/blogType")
public class BlogTypeController {
    private static final int PAGE_SIZE = 2;

    private BlogTypeService blogTypeService;
    private BlogService blogService;

    @Autowired
    public void setBlogTypeService(BlogTypeService blogTypeService) {
        this.blogTypeService = blogTypeService;
    }

    @Autowired
    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    @RequestMapping("/queryList")
    public String queryList(String queryPageNum, String name, String startTime, String endTime, HttpServletRequest request, HttpSession session) {
        System.out.println(queryPageNum);
        if (name == null) {
            name = "";
        }
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(queryPageNum);
        } catch (NumberFormatException ignored) {
        }
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        // 获取登录用户的博客类型
        List<BlogType> blogTypeList = blogTypeService.findAll(loginUser.getId(), "%" + name + "%", startTime, endTime);
        // 放到Map中
        Map<String, Object> pageInfoMap = new HashMap<>();
        List<BlogType> thePageBlogTypeList;
        int fromIndex = (pageNum - 1) * PAGE_SIZE;
        try {
            thePageBlogTypeList = blogTypeList.subList((pageNum - 1) * PAGE_SIZE, pageNum * PAGE_SIZE);
        } catch (IndexOutOfBoundsException e) {
            if (fromIndex > blogTypeList.size()) {
                pageNum = 1;
                thePageBlogTypeList = blogTypeList.subList(0, blogTypeList.size());
            } else {
                thePageBlogTypeList = blogTypeList.subList((pageNum - 1) * PAGE_SIZE, blogTypeList.size());
            }
        }
        pageInfoMap.put("results", thePageBlogTypeList);
        pageInfoMap.put("totalPage",
                blogTypeList.size() % PAGE_SIZE == 0 ? blogTypeList.size() / PAGE_SIZE : blogTypeList.size() / PAGE_SIZE + 1);
        pageInfoMap.put("pageNum", pageNum);

        Map<String, Object> queryInfoMap = new HashMap<>();
        queryInfoMap.put("pageNum", pageNum);
        queryInfoMap.put("name", name);
        Map<String, Object> queryModelMap = new HashMap<>();
        queryModelMap.put("startTime", startTime);
        queryModelMap.put("endTime", endTime);
        // 存域
        request.setAttribute("pageInfo", pageInfoMap);
        request.setAttribute("queryInfo", queryInfoMap);
        request.setAttribute("queryModel", queryModelMap);
        // 转发
        return "blogType/types";
    }

    /**
     * 创建新的博客类型
     * 注意一个人的博客类型不可以一样 但是可以和别人的一样
     *
     * @param blogType 新的博客类型
     * @param response response
     * @param session  session
     * @return 创建结果json
     */
    @PostMapping("/create")
    @ResponseBody
    public String creat(BlogType blogType, HttpServletResponse response, HttpSession session) {
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        // 检验必填字段 分类名称是否为空 或 空字符串
        System.out.println(blogType);
        if (StringUtils.isEmpty(blogType.getTitle())) {
            return "{\"success\":false,\"message\":\"分类名称不能为空\"}";
        }
        // 检查博客的title是否有重复 即自己的不能重复
        BlogType theTitleBlogType = blogTypeService.findTheUserBlogTypeByTitle(blogType.getTitle(), loginUser.getId());
        if (theTitleBlogType != null) {
            // 已经存在相同标题的博客类型
            return "{\"success\":false,\"message\":\"已存在分类类型为" + blogType.getTitle() + "的博客类型\"}";
        } else {
            // 关键字段不为空 执行插入操作
            // 设置userId为登录的userId
            blogType.setUserId(loginUser.getId());
            // 设置insertUser为登录的nickName
            blogType.setInsertUser(loginUser.getNickName());
            boolean b = blogTypeService.creat(blogType);
            return b ? "{\"success\":true,\"message\":\"创建新分类成功\"}" : "{\"success\":false,\"message\":\"创建新分类失败\"}";
        }
    }

    /**
     * 根据gid删除博客类型
     *
     * @param gid      要删除的博客类型的id
     * @param response response
     * @return 结果json字符串
     */
    @RequestMapping("/{gid}/delete")
    @ResponseBody
    public String delete(@PathVariable int gid, HttpServletResponse response) {
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        // 用来保存响应的信息
        Map<Object, Object> map = new HashMap<>();
        // 判断要删除的blogType的gid是否关联的有blog
        if (!blogService.findByBlogTypeId(gid).isEmpty()) {
            return "{\"success\":false,\"message\":\"关联有博客删除失败\"}";
        }
        if (blogTypeService.deleteById(gid)) {
            return "{\"success\":true,\"message\":\"删除成功\"}";
        } else {
            return "{\"success\":false,\"message\":\"删除失败\"}";
        }
    }

    /**
     * 根据id查询指定的博客类型
     *
     * @param response response
     * @param id       要查询的博客类型的id
     * @return 博客类型json map{success:..., data:...}
     */
    @RequestMapping("/{id}/info")
    @ResponseBody
    public String info(HttpServletResponse response, @PathVariable int id) {
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        // 根据id查询博客类型
        BlogType blogType = blogTypeService.findById(id);
        HashMap<String, Object> map = new HashMap<>();
        String data = null;
        if (blogType != null) {
            map.put("data", blogType);
            map.put("success", true);
            try {
                data = new ObjectMapper().writeValueAsString(map);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        } else {
            data = "{\"success\":false,\"message\":\"未找到相关信息\"}";
        }
        return data;
    }

    /**
     * 更新博客类型
     *
     * @param blogType 博客类型
     * @param response 响应
     * @param session  session
     * @return 修改结果
     */
    @PostMapping("/update")
    @ResponseBody
    public String update(BlogType blogType, HttpServletResponse response, HttpSession session) {
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        // 检验必填字段 分类名称是否为空 或 空字符串
        if (StringUtils.isEmpty(blogType.getTitle())) {
            return "{\"success\":false,\"message\":\"分类名称不能为空\"}";
        }
        // 关键字段不为空 执行修改操作
        // 检查博客的title是否有重复
        BlogType theTitleBlogType = blogTypeService.findTheUserBlogTypeByTitle(blogType.getTitle(), loginUser.getId());
        //根据title查到的博客类型
        if (theTitleBlogType != null && !Objects.equals(theTitleBlogType.getId(), blogType.getId())) {
            // 已经存在相同标题的博客类型
            return "{\"success\":false, \"message\":\"已存在分类类型为" + blogType.getTitle() + "的博客类型\"}";
        }
        boolean b = blogTypeService.update(blogType);
        return b ? "{\"success\":true,\"message\":\"修改成功\"}" : "{\"success\":false,\"message\":\"修改失败\"}";
    }
}
